from rest_framework import serializers
from apps.headline.models import Article
from .models import User
from apps.question.models import Label, Reply, Question
from apps.recruit.models import Enterprise, Recruit


class QuestionSerializer(serializers.ModelSerializer):
    """Question 规格表序列化器"""
    class Meta:
        model = Question
        fields = "__all__"

    def __str__(self):
        return self.user


class LabelsSerializer(serializers.ModelSerializer):
    '''Label规格表序列化器'''
    class Meta:
        model = Label
        fields = "__all__"


class EnterpriseSerializer(serializers.ModelSerializer):
    '''企业规格表序列化器'''
    class Meta:
        model = Enterprise
        fields = "__all__"


class ReplySerializer(serializers.ModelSerializer):
    '''回复规格表序列化器'''

    user = serializers.PrimaryKeyRelatedField(read_only=True)
    content = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Reply
        # fields = ("id", "content", "createtime", "useful_count", 'problem', "unuseful_count", "user")
        fields = ("id", "content", "createtime", 'problem', "user", 'useful_count', 'type')


class ArticleSerializer(serializers.ModelSerializer):
    '''文章阅读规格表序列化器'''
    user = serializers.CharField(read_only=True)

    class Meta:
        model = Article
        fields = '__all__'




class UserSerializer(serializers.ModelSerializer):

    answer_question = serializers.SerializerMethodField()
    username = serializers.CharField(read_only=True)
    questions = QuestionSerializer(many=True)
    labels = LabelsSerializer(many=True)
    collected_articles = serializers.SerializerMethodField()
    enterpises = EnterpriseSerializer(many=True)

    class Meta:
        model = User
        fields = '__all__'

    def get_answer_question(self, obj):
        reply = Reply.objects.filter(user=obj)
        return ReplySerializer(reply, many=True).data

    def get_collected_articles(self, obj):
        articles = Article.objects.filter(user=obj)
        return ArticleSerializer(articles, many=True).data



from django_redis import get_redis_connection
import re, jwt
from django.conf import settings
from datetime import timedelta, datetime

class RegisterSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'token', 'avatar', 'sms_code']
        extra_kwargs = {
            'username': {
                'min_length': 4,
                'max_length': 20,
                'error_messages': {
                    'min_length': '用户名为4-20个字符!',
                    'max_length': '用户名为4-20个字符!',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 4,
                'max_length': 20,
                'error_messages': {
                    'min_length': '密码为4-20个字符',
                    'max_length': '密码为4-20个字符',
                }
            }
        }

    def validate_mobile(self, value):
        print(value)
        if not re.match(r'^1[345789]\d{9}$', value):
            raise serializers.ValidationError('手机格式不正确')
        return value

    def validate(self, attrs):
        # 链接redis数据库
        sms_redis_client = get_redis_connection('verify_code')
        # 取出mobile
        mobile = attrs.get('mobile')
        print(mobile)
        # 取出验证码
        mobile_redis = sms_redis_client.get("sms_%s" % mobile)
        # 取出验证码
        sms = attrs.get('sms_code')
        print(mobile_redis)
        if mobile_redis is None:
            raise serializers.ValidationError('验证码失效')
        if sms != mobile_redis.decode():
            raise serializers.ValidationError('验证码错误')
        return attrs

    def create(self, validated_data):
        del validated_data['sms_code']
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        print(user.mobile)
        user.save()
        # 3.设置载体
        payload = {
            "user_id": user.id,
            "username": user.username,
            # 设置过期时间
            'exp': datetime.utcnow() + timedelta(days=1)
        }

        # 4.加密
        token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        user.token = token.decode()
        return user


# 修改擅长技术
class UpdateLabelSerializer(serializers.ModelSerializer):
    # labels = serializers.PrimaryKeyRelatedField(required=True, many=True, queryset=Label.objects.all())

    class Meta:
        model = User
        fields = '__all__'